package com.shopoo.behavior.app;

import com.shopoo.behavior.api.ReadService;
import com.shopoo.behavior.app.converter.AppConverter;
import com.shopoo.behavior.dto.cqe.BehaviorReadReadCmd;
import com.shopoo.behavior.infrastructure.database.dataobject.TBehaviorRead;
import com.shopoo.behavior.infrastructure.database.mapper.ReadMapper;
import com.shopoo.flyer.api.PromotionService;
import com.szmengran.cola.dto.Response;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Description: 阅读记录服务
 * @Package com.szmengran.behavior.service.impl
 * @date Mar 4, 2019 1:55:30 PM
 * @author <a href="mailto:android_li@sina.cn">Joe</a>
 */
@Slf4j
@Service
public class ReadServiceImpl implements ReadService {

    private static final ExecutorService executor = Executors.newFixedThreadPool(100);

    @Value("${behavior.one_person_max_read_count}")
    private int maxReadCount;

    @Resource
    private ReadMapper readMapper;

    @DubboReference
    private PromotionService promotionService;


    @Override
    public Response readCount(BehaviorReadReadCmd behaviorReadReadCmd) {
        // 传单号或公众号openid为空时，直接返回
        if (StringUtils.isEmpty(behaviorReadReadCmd.getOpenid()) || StringUtils.isEmpty(behaviorReadReadCmd.getPromotionid())) {
            return new Response();
        }
        int count = readMapper.readCountByOpenid(behaviorReadReadCmd.getPromotionid(), behaviorReadReadCmd.getOpenid());
        if (count < maxReadCount) {
            executor.submit(() -> {
                try {
                    promotionService.addRead(behaviorReadReadCmd.getPromotionid());
                } catch (Exception e) {
                    log.error("", e);
                }
            });
        }
        executor.submit(() -> {
            try {
                TBehaviorRead toTBehaviorRead = AppConverter.INSTANCE.toTBehaviorRead(behaviorReadReadCmd);
                readMapper.insert(toTBehaviorRead);
            } catch (Exception e) {
                log.error("", e);
            }
        });
        return Response.buildSuccess();
    }

}
